package com.frame.framework.bean.factory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Description 用来存储多个 propertyValue 对象
 * @Author Mokairui
 * @Since 2021/11/26
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {
    // 定义 List 集合, 用来存储 propertyValue 对象
    private List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        this.propertyValueList = propertyValueList == null ? new ArrayList<>() : propertyValueList;
    }

    // 获取指定名称的 propertyValue 对象
    public PropertyValue getPropertyValue(String name) {
        return propertyValueList.stream()
                .filter(it -> it.getName().equals(name))
                .findFirst()
                .orElseGet(null);
    }

    // 添加 PropertyValue 对象, 如果名称重复则覆盖
    public MutablePropertyValues add(PropertyValue pv) {
        for (int i = 0; i < propertyValueList.size(); i++) {
            if (propertyValueList.get(i).getName().equals(pv.getName())) {
                propertyValueList.set(i, pv);
                return this;
            }
        }
        propertyValueList.add(pv);
        return this;
    }

    // 获取所有的 propertyValue 对象, 返回以数组的形式
    public PropertyValue[] getPropertyValues() {
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    // 判断是否含有此
    public boolean contains(String name) {
        return getPropertyValue(name) != null;
    }

    // 判断集合是否为空
    public boolean isEmpty() {
        return propertyValueList.isEmpty();
    }

    // 获取迭代器对象
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
